import md5 from 'js-md5'
import { urlEncode } from './index'
const baseUrl = process.env.API_BASE_URL

function request(url, method, data) {
    wx.showLoading({
        title: '加载中' // 数据请求前loading
    })
    return new Promise((resolve, reject) => {
        // const appid = 'wxac10e0b6b389fe20'
        const secretKey = '66d9a3240d3461ad07df52ccbc8da2fc'
        const arrData = {
            // appid,
            ...data
        }
        let newData = {}
        let keysSorted = Object.keys(arrData).sort()
        for (let i = 0; i < keysSorted.length; i++) {
            newData[keysSorted[i]] = arrData[keysSorted[i]];
        }
        const sign = md5(`${urlEncode(newData).slice(1)}${secretKey}`).toUpperCase()
        const request = {
            // appid,
            sign,
            ...data
        }
        wx.request({
            url: baseUrl + url, // 接口地址
            method: method,
            data: request,
            header: {
                "content-type": "application/x-www-form-urlencoded",
                "token": wx.getStorageSync('token')
            },
            success: function (res) {
                if (res.data.succeed === 1) {
                    resolve(res.data.datas)
                } else {
                    wx.showModal({
                        content: res.data.returnMsg,
                        showCancel: false,
                        confirmText: "好的"
                    })
                }
            },
            fail: function (res) {
                wx.showLoading({
                    title: '请检查网络'
                })
                setTimeout(function () {
                    wx.hideLoading()
                }, 5000)
            },
            complete: function () {
                wx.hideLoading()
            }
        })
    })
}

function get(obj) {
    return request(obj.url, 'GET', obj.data)
}

function post(obj) {
    return request(obj.url, 'POST', obj.data)
}

export default {
    request,
    get,
    post
}
